package com.palm.platform.service;

import com.palm.core.util.CollectionUtil;
import com.palm.platform.domain.Role;
import com.palm.platform.domain.RolePermission;
import com.palm.platform.domain.UserRole;

import org.noear.solon.annotation.Inject;

import org.noear.solon.data.annotation.Tran;
import org.noear.solon.extend.aspect.annotation.Service;
import org.noear.solon.extend.sqltoy.annotation.Db;
import org.sagacity.sqltoy.dao.SqlToyLazyDao;

import java.util.Collection;
import java.util.List;
import java.util.Set;

@Service
public class RoleService {
    @Db
    SqlToyLazyDao dao;

    public Set<String> getPermissionOfRole(String role){
        RolePermission query=new RolePermission();
        query.setRole(role);
        List<RolePermission> permissions= dao.findBySql("select * from "+RolePermission.TABLE+" where role=:role",query);
        return CollectionUtil.mapToSet(permissions, it->it.getPermission());
    }
    public Set<String> getPermissionOfUser(String username){
        RolePermission query=new RolePermission();
        query.setRole(username);
        List<RolePermission> permissions= dao.findBySql("select DISTINCT(a.permission)  permission from t_role_permission a INNER JOIN t_user_role b on a.role=b.role where b.user_name=:role",query);
        return CollectionUtil.mapToSet(permissions, it->it.getPermission());
    }
    public Set<String> getRoleOfUser(String username){
        List<UserRole> permissions= dao.findBySql("select role from t_user_role  where user_name=:username",new UserRole(username));
        return CollectionUtil.mapToSet(permissions, it->it.getRole());
    }
    public Set<String> getAllRole(){
        List<Role> roles=dao.findBySql("select * from t_role",new Role());
        return CollectionUtil.mapToSet(roles, it->it.getSn());
    }

    /**
     * 删除用户原有的role,新增指定roles
     * @param username
     * @param roles
     */
    @Tran
    public void updateRolesOf(String username, Collection<String> roles) {
       dao.executeSql("delete from t_user_role where user_name=:username",new UserRole(username));
       List<UserRole> addUserRoles= CollectionUtil.map(roles,role->new UserRole(username,role));
       dao.saveAll(addUserRoles);
    }
}
